package cn.edu.sdjzu.controller;

import cn.edu.sdjzu.entity.School;
import cn.edu.sdjzu.exception.BaseException;
import cn.edu.sdjzu.factory.ServiceFactory;
import cn.edu.sdjzu.service.SchoolService;
import cn.edu.sdjzu.util.Condition;
import cn.edu.sdjzu.util.ControllerHelper;
import cn.edu.sdjzu.util.JSONUtil;
import cn.edu.sdjzu.util.Pagination;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;


@WebServlet("/schoolCreate.ctl")
public class SchoolCreateCtrl extends HttpServlet {
    //LoggerFactory.getLogger 是SLF4J提供的工厂方法，用于获取类的Logger实例
    //private static final Logger log = LoggerFactory.getLogger(SchoolCreateCtrl.class);
    //获取schoolService对象
    private SchoolService schoolService = ServiceFactory.getService(SchoolService.class, "SchoolServiceImpl");
    //ServiceFactory.getService声明了必检查异常BaseException, InvocationTargetException，本类不得不定义构造器声明异常
    public SchoolCreateCtrl() throws BaseException, InvocationTargetException {
    }
    /**
    {
        "description": "管理工程",
            "id": 2,
            "no": "02",
            "remarks": ""
    }
    **/
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置请求字符编码为UTF-8
        request.setCharacterEncoding("UTF-8");
        //根据request对象，获得代表参数的JSON字串
        String school_json = JSONUtil.getJSON(request);
        //将JSON字串解析为School对象
        School schoolToAdd = JSON.parseObject(school_json, School.class);
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象message，以便往前端响应信息
        JSONObject msg = new JSONObject();
        //在数据库表中增加School对象
        try {
            schoolService.add(schoolToAdd);
            msg.put("msg", "增加成功");
            msg.put("code","200");
            //log.error("成功！:");
        }catch (SQLException e){
            msg.put("msg", "数据库操作异常");
            msg.put("code","200");
            // 记录SQLException的错误信息
            //log.error("数据库操作异常: {}", e.getMessage(), e);
        }catch(Exception e){
            msg.put("msg", "网络异常");
            msg.put("code","200");
            // 记录其它的错误信息
            //log.error("网络异常: {}", e.getMessage(), e);
        }
        //响应message到前端
        response.getWriter().println(JSON.toJSONString(msg));
    }
   
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //授权验证
//        String idInToken = JwtUtil.parseToken(request);
//        log.debug("id in token=" + idInToken);

        //创建JSON对象message_jsonObj，以便往前端响应信息
        JSONObject message_jsonObj = new JSONObject();
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象，可能含有分页信息、查询条件
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null) {
            message_jsonObj.put("msg", "未收到请求信息！");
            response.getWriter().println(message_jsonObj);
            return;
        }
        try {
            //读取分页信息，形成分页对象{"pagination":{"pageNo":1,"pageSize":2}}
            //将JSON字串解析为Pagination对象
            Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
            //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
            List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
            //分页获得所有学院
            Collection<School> schools = ServiceFactory.getService
                    (SchoolService.class,"SchoolServiceImpl").findAll(pagination, conditionList);

//            String schools_json = JSON.toJSONString(
//                    schools, SerializerFeature.DisableCircularReferenceDetect);
            message_jsonObj.put("totalNum", pagination.getTotalNum());
            message_jsonObj.put("records", schools);
            //响应message_jsonObj到前端
            response.getWriter().println(message_jsonObj);
        } catch (BaseException e) {
            message_jsonObj.put("msg", e.getMessage());
            response.getWriter().println(message_jsonObj);
            //log.error(e.getMessage());
        } catch (SQLException e) {
            message_jsonObj.put("msg", "数据库操作异常");
            response.getWriter().println(message_jsonObj);
            //log.error(e.getMessage());
        } catch (Exception e) {
            message_jsonObj.put("msg", "网络异常");
            response.getWriter().println(message_jsonObj);
        }
    }

//    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//
//        //授权验证
////        String idInToken = JwtUtil.parseToken(request);
////        log.debug("id in token=" + idInToken);
//
//        //创建JSON对象message_jsonObj，以便往前端响应信息
//        JSONObject message_jsonObj = new JSONObject();
//
//        //设置响应字符编码为UTF-8
//        response.setContentType("application/json;charset=UTF-8");
//        //将request body转换为JSON字串
//        String req_jsonStr = JSONUtil.getJSON(request);
//        //将request body解析为JSONObject对象，可能含有分页信息、查询条件
//        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
//        //如果请求body为空
//        if (req_jsonObj == null) {
//            message_jsonObj.put("msg","未收到请求信息！");
//            response.getWriter().println(message_jsonObj);
//            return;
//        }
//
//        try {
//            //读取分页信息，形成分页对象
//            //示例{"pageNo":1,"pageSize":2}
//            //将JSON字串解析为Pagination对象
//            Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
//            //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
//            List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
//            //响应多个教师信息，其中conditionList, pagination两个对象引用为空是可能的
//            this.responseSchools(response, pagination, conditionList);
//
//        }catch (SQLException e){
//            message_jsonObj.put("msg", "数据库操作异常");
//            response.getWriter().println(message_jsonObj);
//            e.printStackTrace();
//        }catch(Exception e){
//            message_jsonObj.put("msg", "网络异常");
//            response.getWriter().println(message_jsonObj);
//        }
//    }
}

